import React, { Suspense } from 'react'
import { routes } from './routes'
import { BrowserRouter, Routes, Route, useLocation, Navigate } from 'react-router-dom'

interface PropsType {
	children: JSX.Element
}

// 路由拦截: 前置守卫
const BeforeRouter: React.FC<PropsType> = ({ children }) => {
	const whiteList = ['/login'];
	const { pathname } = useLocation()
	// 访问的是不是白名单页面
	if (whiteList.includes(pathname)) {
		// 说明当前访问的是白名单页面  其实就是登录页面
		return children
	} else {
		// 访问的不是白名单 非登录页面
		const token = localStorage.getItem('token');
		if (token) {
			return children
		} else {
			return <Navigate to="/login"></Navigate>
		}
	}
}

const Router = () => {
	return (
		<Suspense>
			<BrowserRouter>
				<Routes>
					{
						routes.map((v, i) => {
							return <Route path={v.path} element={<BeforeRouter>{v.element}</BeforeRouter>} key={i}></Route>
						})
					}
				</Routes>
			</BrowserRouter>
		</Suspense>
	)
}

export default Router